package org.demo.url;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * Created by tangwy on 2017/8/19.
 */
public class BrokenPointDownload {
    private String urlPath;
    private String filePath;
    private HttpURLConnection connection;
    private boolean isContinue;

    public BrokenPointDownload(String urlPath, String filePath) {
        this.urlPath = urlPath;
        this.filePath = filePath;
    }

    public void download() throws MalformedURLException, IOException {
        String tempFilePath = filePath + ".temp";
        File tempFile = new File(tempFilePath);
        File downloadFile = new File(filePath);
        long alreadyDownloadLength = 0;
        if (tempFile.exists()) {
            alreadyDownloadLength = tempFile.length();
        } else {
            tempFile.createNewFile();
            downloadFile.createNewFile();
        }
        URL url = new URL(urlPath);
        connection = (HttpURLConnection) url.openConnection();
        connection.setRequestProperty("RANGE","bytes="+alreadyDownloadLength+"-");
        /*if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
            throw new RuntimeException("连接资源失败");
        }*/
        Map<String, List<String>> headerFields = connection.getHeaderFields();
        Set<Map.Entry<String,List<String>>> entrySet=headerFields.entrySet();
        for(Map.Entry<String,List<String>> entry:entrySet){
            System.out.println("key="+entry.getKey()+",value="+entry.getValue());
        }
        long contentLength = getContentLength();
        if (contentLength == -1) {
            throw new RuntimeException("获取文件长度失败");
        }

        System.out.println(contentLength);
        InputStream inputStream = connection.getInputStream();
        System.out.println("已经下载了========" + alreadyDownloadLength);
        System.out.println("剩余========" + (contentLength));
        byte[] bytes = new byte[4096];
        int readLength;
        long aa = 0;
        try (RandomAccessFile tempRaf = new RandomAccessFile(tempFile, "rw");
             RandomAccessFile downloadRaf = new RandomAccessFile(downloadFile, "rw")) {
            downloadRaf.setLength(contentLength+alreadyDownloadLength);
            //inputStream.skip(alreadyDownloadLength);
            downloadRaf.seek(alreadyDownloadLength);
            while ((readLength = inputStream.read(bytes)) > 0) {
                aa += readLength;
                //System.out.println("读取了长度==" + readLength);
                downloadRaf.write(bytes, 0, readLength);
                alreadyDownloadLength+=readLength;
                tempRaf.setLength(alreadyDownloadLength);
                //设置是否终止下载，为了测试断点续传
                if (!isContinue) {
                    break;
                }
            }

            System.out.println("本次下载长度==" + aa);
        }
        if (readLength <= 0) {
            tempFile.delete();
        }
        if (inputStream != null) {
            inputStream.close();
            inputStream = null;
        }
        if (connection != null) {
            connection.disconnect();
        }
    }

    private long getContentLength() throws IOException {

        long contentLength = connection.getContentLength();
        //connection.disconnect();
        return contentLength;
    }

    public boolean isContinue() {
        return isContinue;
    }

    public void setIsContinue(boolean isContinue) {
        this.isContinue = isContinue;
    }

}
